Enums
-
Enums .
Similarities between Enums and Structs
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
-
The name of each enum variant that we define also becomes a function that constructs an instance of the enum.
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), }-
Quithas no data associated with it at all. -
Movehas named fields, like a struct does. -
Writeincludes a singleString. -
ChangeColorincludes threei32values.
-
-
Weβre also able to define methods on enums using
impl.impl Message { fn call(&self) { // method body } } let m = Message::Write(String::from("hello")); m.call();